<?php

namespace app\common\middleware;

use support\Request;
use support\Response;
use Webman\Http\Response as WebmanResponse;

class StaticCors
{
    /**
     * 静态资源跨域中间件
     * 专门针对所有静态资源文件
     */
    public function process(Request $request, callable $next)
    {
        $path = $request->path();
        
        // 检查是否为静态文件（基于文件扩展名）
        $isStaticFile = $this->isStaticFile($path);
        
        // 处理OPTIONS预检请求（针对所有请求）
        if ($request->method() === 'OPTIONS') {
            $response = new Response(200, []);
            $this->addCorsHeaders($response, $request);
            return $response;
        }
        
        // 处理正常请求
        $response = $next($request);
        
        // 为所有静态文件和storage目录添加CORS头
        if ($isStaticFile || str_starts_with($path, 'storage/')) {
            $this->addCorsHeaders($response, $request);
        }
        
        return $response;
    }
    
    /**
     * 判断是否为静态文件
     */
    private function isStaticFile(string $path): bool
    {
        $extension = pathinfo($path, PATHINFO_EXTENSION);
        if (!$extension) {
            return false;
        }
        
        $staticExtensions = [
            'jpg', 'jpeg', 'png', 'gif', 'ico', 'svg', 'webp',
            'css', 'js', 'map', 'json', 'txt', 'xml',
            'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
            'zip', 'rar', 'tar', 'gz', '7z',
            'mp3', 'mp4', 'avi', 'wmv', 'flv', 'mov',
            'woff', 'woff2', 'ttf', 'otf', 'eot'
        ];
        
        return in_array(strtolower($extension), $staticExtensions);
    }
    
    /**
     * 添加CORS头
     */
    private function addCorsHeaders($response, Request $request): void
    {
        $origin = $request->header('origin');
        
        // 如果存在Origin头，则使用具体的Origin值，而不是通配符
        if ($origin) {
            $allowOrigin = $origin;
        } else {
            $allowOrigin = '*';
        }
        
        // 确保响应对象存在
        if (!$response) {
            return;
        }
        
        if ($response instanceof Response) {
            $response->header('Access-Control-Allow-Origin', $allowOrigin);
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD');
            $response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin, Cache-Control, Pragma, Expires, X-CSRF-TOKEN, Range');
            $response->header('Access-Control-Allow-Credentials', 'true');
            $response->header('Access-Control-Max-Age', '86400');
            $response->header('Access-Control-Expose-Headers', 'Content-Disposition, X-Filename, Content-Length, Accept-Ranges, Content-Range');
        } elseif ($response instanceof WebmanResponse) {
            $response->withHeader('Access-Control-Allow-Origin', $allowOrigin);
            $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD');
            $response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin, Cache-Control, Pragma, Expires, X-CSRF-TOKEN, Range');
            $response->withHeader('Access-Control-Allow-Credentials', 'true');
            $response->withHeader('Access-Control-Max-Age', '86400');
            $response->withHeader('Access-Control-Expose-Headers', 'Content-Disposition, X-Filename, Content-Length, Accept-Ranges, Content-Range');
        }
    }
}